// 频道的数据操作

import { getUserChannels, getChannels } from '@/api/channels'

export default {
  namespaced: true,
  state: {
    // 我的频道数据
    channelList: [],
    // 所有频道数据
    allChannelList: []
  },
  mutations: {
    setChannelList(state, payload) {
      state.channelList = payload
    },
    addChannelList(state, payload) {
      state.channelList.push(payload)
    },
    delChannelList(state, payload) {
      state.channelList = state.channelList.filter(
        item => item.id !== payload.id
      )
    },
    setAllChannelList(state, payload) {
      state.allChannelList = payload
    }
  },
  actions: {
    async actions_getChannelList(context) {
      const res = await getUserChannels()
      console.log(res)
      // this.channelList = res.data.channels
      context.commit('setChannelList', res.data.channels)
    },
    async actions_getAllChannelList(context) {
      const res = await getChannels()
      context.commit('setAllChannelList', res.data.channels)
    }
  },
  getters: {
    // 计算属性 ==> 需要计算出可选频道
    // 公式： 所有频道数据 - 我的频道数据 ==> 可选的
    optionsChannelList(state) {
      // error
      // return state.allChannelList - state.channelList
      // 正确： 来遍历所有的频道数组，过滤出在我的频道里面没有的数据

      /* return state.allChannelList.filter(item => {
        // item 是每一项 {id, name}

        const res = state.channelList.some(channel => {
          return channel.id === item.id
        })
        console.log('res', res)
        // true  ==> 表示该频道已经在我的频道有了
        // false ==> 属于可选频道

        if (res) {
          return false
        } else {
          return true // 符合条件为true，就会被过滤出去
        }
      }) */

      // 以上代码简化
      return state.allChannelList.filter(
        item => !state.channelList.some(channel => channel.id === item.id)
      )
    }
  }
}

/*
;[(10, 20, 30)].filter(item => {
  return item > 15
})
 */
